package com.shaolei.server_thread;
import java.util.ArrayList;
import java.util.Queue;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import com.shaolei.server.TCPEchoServer;

public class RW_myQ {
	private ReadWriteLock rwl = new ReentrantReadWriteLock();
	public String[] reveive_analyse(String clientid, String receive){
		String[] parts= receive.split("&&");
		String[] info_array= new String[2];
		if (parts[0].equals("$$REQUEST")) {
			StringBuilder builder = new StringBuilder();
			ArrayList<String> userlist=new TCPEchoServer().get_active_client();
			for(String s : userlist) builder.append(s);
			info_array[0]= clientid;
			info_array[1]= builder.toString();
		}
		else if (parts[0].equals("$$END")) {
			info_array[0]=clientid;
			info_array[1]="$$END_FROM_CLIENT";
		}
		else if (parts[0].equals("$$MSSG")){
			String forwardid= parts[1];
			if (forwardid.equals("offline")) {
				info_array[0]= clientid;
				info_array[1]= "$$This guy is offline";
			}
			else {
				info_array[0]= forwardid;
				info_array[1]= receive;
			}
		}
		else System.out.println("ERROR::rw_myQ::"+"reveive_analyse "+receive);
		return info_array;
	}
	
	public boolean put(String clientid, String receive) {
		boolean status=true;
		try {
			String[] info_array= reveive_analyse(receive, clientid);
			rwl.writeLock().lock();
			new Server_out().add2myQ(info_array);
			if (info_array[1].equals("$$END_FROM_CLIENT")) status=false;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			rwl.writeLock().unlock();
		}
		return status;
	}
	
	public String[] get() {
		String[] info_array={};
		Queue<String[]> myQ= new Server_out().get_myQ();
		try {
			rwl.writeLock().lock();
	 		if (!myQ.isEmpty()) {
	 			info_array= myQ.peek();
	 			myQ.remove();
	 		}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			rwl.writeLock().unlock();
		}
		return info_array;
	}
}